import json
import re
import uuid
from biz.config.api_config import ApiConfig
from biz.utils.request_util import RequestUtil
from biz.utils.logger import logger
from biz.config.settings import get_sql_context

vn = get_sql_context()
search_sql = """
            SELECT
                t2.alone_lamp_control_id,
                t3.alone_lamp_id,
                t4.alone_lamp_code,
                {dimmingValue} AS dimming_value 
            FROM
                device.l_lamppost t1
                JOIN device.l_alonelamp_control t2 ON t2.lamp_post_id = t1.lamp_post_id
                JOIN device.l_alonelamp_control_middle t3 ON t3.alone_lamp_control_id = t2.alone_lamp_control_id
                JOIN device.l_alonelamp t4 ON t4.alone_lamp_id = t3.alone_lamp_id 
            WHERE
                t1.lamp_post_code = '{lamppostCode}'
"""

road_sql = """
SELECT
	t1.lamp_post_code,
	t4.alone_lamp_control_id,
	t5.alone_lamp_id,
	t6.alone_lamp_code,
	{dimmingValue} AS dimming_value 
FROM
	device.l_lamppost t1,
	device.b_street t2,
	device.b_street_side t3,
	device.l_alonelamp_control t4,
	device.l_alonelamp_control_middle t5,
	device.l_alonelamp t6 
WHERE
	t2.street_name = '{roadName}' 
	AND t1.street_id = t2.street_id 
	AND t1.street_side_id = t3.street_side_id 
	AND t4.lamp_post_id = t1.lamp_post_id 
	AND t5.alone_lamp_control_id = t4.alone_lamp_control_id 
	AND t6.alone_lamp_id = t5.alone_lamp_id
"""

# token_param = {
#     "url": "http://123.232.113.233:55000/jwtcenter/JWTInfoController/getToken",
#     "data": {"subject": "telchina", "loginPwd": "545DBA10DECB60A1F33E7D8BCEE34FE3B7E1621208DC14F741C910DDF4FC0FB9EEE9592E7C4E0D41191833549F8C7CA9"}
# }

#command_url = "http://123.232.113.233:55100/smartpole/light/command/setDimmingValue"


class Command:
    def get_uuid(self):
        return str(uuid.uuid1())

    def execution_command(self, res):
        """
        通过照明系统发送调光指令（同步版本）
        """
        def execute_business_command(lamppostCode, dimmingValue, on_off):
            try:
                params = {
                    "lampPostCode": lamppostCode,
                    "dimmingValue": dimmingValue
                }
                data = {'json': f'{params}'}
                url = ApiConfig.PATHS["smartlight_light_command"]["dimming"]
                util = RequestUtil()
                
                # 使用同步方法
                res = util.post_form(url, data=data)
                message = f"{lamppostCode}{on_off}指令发送失败"
                if res is not None:
                    res_json = res.json()
                    if res_json.get("code") == "200":
                        message = f"{lamppostCode}{on_off}指令发送成功"
                return message
            except Exception as e:
                logger.error(f"请求失败: {e}")
                return f"{lamppostCode}{on_off}指令发送失败"

        def analysis_instructions(commandObj):
            if commandObj.get("error") is not None:
                return commandObj["error"]
            lamppostCode = commandObj["lamppostCode"]
            dimmingValue = commandObj["dimmingValue"]
            on_off = '关灯' if dimmingValue == 0 else '开灯'
            message = []
            if isinstance(lamppostCode, list):
                for code in lamppostCode:
                    message.append(execute_business_command(code, dimmingValue, on_off))
                return "<br>".join(str(item) for item in message)
            else:
                return execute_business_command(lamppostCode, dimmingValue, on_off)

        try:
            if isinstance(res, list):
                res_data = []
                for item in res:
                    res_data.append(analysis_instructions(item))
                return "<br>".join(str(item) for item in res_data)
            elif isinstance(res, str):
                commandData = json.loads(res)
                return analysis_instructions(commandData)
            else:
                return analysis_instructions(res)
        except Exception as e:
            logger.error(f"json格式化报错: {e}")
            return "指令发送失败"

    def execution_command_road(self, res):
        def execute_business_command(roadName, roadSide, dimmingValue, on_off):
            # 根据道路查询
            sql = road_sql.format(roadName=roadName, dimmingValue=dimmingValue)
            if roadSide or roadSide is not None:
                sql = sql + f" \n AND t3.street_side_name = '{roadSide}'"
            vn.connect_to_postgres()
            data = vn.run_sql(sql=sql)
            if data is not None and data.size > 0:
                try:
                    params = []
                    for index, row in data.iterrows():
                        params.append({
                            "aloneLampControlId": row["alone_lamp_control_id"],
                            "aloneLampId": row["alone_lamp_id"],
                            "aloneLampCode": row["alone_lamp_code"],
                            "dimmingValue": row["dimming_value"]
                        })
                    # 发送调光指令
                    util = RequestUtil()
                    get_token = util.post_form(token_param["url"], data=token_param["data"])
                    token = json.loads(get_token.text)["resp_data"]["access_token"]
                    response_post = util.post(command_url,
                                              json=params, headers={"X-Authentication-Token": token})
                    if response_post is not None:
                        message = f"{roadName}{on_off}指令发送成功"
                        return message
                except Exception as e:
                    print(f"请求失败: {e}")
                    message = f"{roadName}{on_off}指令发送失败"
                    return message
            else:
                message = f"未找到道路，{roadName}{on_off}指令发送失败"
                return message
        def analysis_instructions(commandObj):
            if commandObj.get("error") is not None:
                return commandObj["error"]
            roadName = commandObj["roadName"]
            roadSide = commandObj["roadSide"]
            dimmingValue = commandObj["dimmingValue"]
            on_off = '关灯' if dimmingValue == 0 else '开灯'
            return execute_business_command(roadName, roadSide, dimmingValue, on_off)
        res_data = []
        commandData = res
        if isinstance(commandData, list):
            for item in commandData:
                res_data.append(analysis_instructions(item))
            return "<br>".join(str(item) for item in res_data)
        else:
            return analysis_instructions(commandData)


    def get_response(self, response, conversation_context):
        start_index_answer = response.rfind("Final Answer")
        if start_index_answer != -1:
            start_index_answer = start_index_answer + len("Final Answer") + 1
            end_index_answer = len(response)
            final_answer = response[start_index_answer:end_index_answer].strip()
            data = re.findall(r"```json(.*)```", final_answer, re.DOTALL)
            if len(data) > 0:
                return True, data[0], conversation_context
            return True, final_answer, conversation_context
        # 解析action
        start_index = response.rfind("Action")
        if start_index == -1:
            start_index_question = response.rfind("Question")
            if start_index_question != -1:
                start_index_thought = response.rfind("Thought")
                start_index_observation = response.rfind("Observation")
                if start_index_thought != -1 and start_index_thought  < start_index_question:
                    end_index_question = start_index_thought
                elif start_index_observation != -1 and start_index_observation < start_index_question:
                    end_index_question = start_index_observation
                else:
                    end_index_question = len(response)

                # end_index_question = response.rfind("Thought")
                # if end_index_question == -1 or end_index_question < start_index_question:
                #     end_index_question = len(response)
                start_index_question = start_index_question + len("Question") + 1
                question = response[start_index_question:end_index_question].strip()
                conversation_context = conversation_context + '\n Action：' + question + '\n ' + 'Observation：'
                return False, question, conversation_context
            conversation_context = conversation_context + '\n ' + 'Observation：'
            return False, "请重新输入", conversation_context
        start_index = start_index + len("Action") + 1
        # 找出Observation之前的内容结束位置
        end_index = response.rfind("Observation")
        if end_index == -1 or end_index < start_index:
            end_index = len(response)
        action = response[start_index:end_index].strip()

        conversation_context = conversation_context + '\n Action：' + action + '\n ' + 'Observation：'
        return False, action, conversation_context



    def extract_router(self, response):
        data = re.findall(r"```json(.*)```", response, re.DOTALL)
        if len(data) > 0:
            return json.loads(data[0])
        return json.loads(response)